import LoadManager from "./LoadManager"






export  class EffectManager  {
    
    private static init: EffectManager = null
    public static get inst(): EffectManager {
        if (!EffectManager.init) {
            EffectManager.init = new EffectManager()
        }
        return EffectManager.init
    }

    private effectId: number[] = [] // 音效id
    private loopEffectUrl: string[] = [] // 循环音效地址

    private _isOn:boolean=true;//是否开启

    public get isOn(){
        return this._isOn;
    }
    public set isOn(isOn:boolean){
        this._isOn=isOn;
    }
    /**
     * 播放音效
     * @param url 路径
     * @param loop 循环
     * @param volume 音量
     * @param cb 回调事件
     */
     async playEffect(url: string, loop: boolean, volume: number, cb?: () => void){
        // 过滤总条件
        if (!this._isOn || !url || url.length == 0) {
            return
        }
        // 加载音频文件
        let clip:cc.AudioClip=LoadManager.get(url, cc.AudioClip)||await LoadManager.load(url, cc.AudioClip)
        // 记录id
        let id=cc.audioEngine.play(clip, loop, volume)
        if (loop) {
            this.loopEffectUrl.push(url)
        }
        // 添加数组
        this.effectId.push(id)
        // 设置音频结束
        cc.audioEngine.setFinishCallback(id, () => {
            cb ? cb() : null
            // 从数组中删除该id
            for (let i = this.effectId.length - 1; i >= 0; i--) {
                if (this.effectId[i] == id) {
                    this.effectId.splice(i, 1)
                }
            }
        })
    }
    /**
     * 停止音效
     */
    public StopEffect(): void {
        // 过滤条件
        if (!this._isOn || this.effectId.length < 1) {
            return
        }
        // 停止音效
        for (let i = this.effectId.length - 1; i >= 0; i--) {
            cc.audioEngine.stop(this.effectId[i])
            this.effectId.splice(i, 1)
        }
    }
    public pauseEffect(): void {
        // 过滤条件
        if (!this._isOn|| this.effectId.length < 1) {
            return
        }
        // 停止音效
        for (let i = this.effectId.length - 1; i >= 0; i--) {
            cc.audioEngine.stop(this.effectId[i])
            this.effectId.splice(i, 1)
        }
    }
    /**
     * 恢复音效
     */
    public ResumeEffect(): void {
        // 过滤数据
        if (!this._isOn || this.loopEffectUrl.length < 1) {
            return
        }
        // 恢复音效
        for (let i = this.loopEffectUrl.length - 1; i >= 0; i--) {
            let url = this.loopEffectUrl[i]
            // 清除数据
            this.loopEffectUrl.splice(i, 1)
            // 播放音效
            this.playEffect(url, true,1)
        }
    }
    /**
     * 播放震动
     */
    public shockEffect(){
        
    }
    /**
     * stopAll
     */
    public stopAllEffect() {
        cc.audioEngine.stopAllEffects();
    }
   
}